#-*- codeing = utf-8 -*-
#@Time : 2020/11/14 15:41
#@Author : 阳某
#@File : my_wsgi_web_server.py
#@Software : PyCharm


from wsgiref.simple_server import  make_server

# 1.路由分发器  ，负责把url匹配到对应的函数
# 2.开发好对应的业务函数
# 3.一个请求来了之后，先走路由分发器，如果找到对应的function，就执行，没有找到就返回404


def cloth(environ,start_response):
    print('cloth page')
    start_response('200 OK', [('Content-type', 'text/html;charset=utf-8')])
    return [bytes('<h1>cloth page!</h1>', encoding='utf-8')]

def book(environ,start_response):
    print('book page')
    start_response('200 OK', [('Content-type', 'text/html;charset=utf-8')])

    data = '''
    <h1>欢迎来到日本人专区</h1>
        <img src='/static/imgs/testimg.gif' />
    <p>老男孩教育</p>
    '''
    return [bytes(data, encoding='utf-8')]

def url_dispacher():
    urls = {
        '/book':book,
        '/cloth':cloth,
    }
    return urls

import re
import os

BASR_DIR = os.path.dirname(__file__)
def img_hander(requests_url):
    '''

    :param requests_url: /static/imgs/testimg.gif
    :return:
    '''
    img_path = re.sub('/static','/static_data',requests_url)
    print('img_path',img_path)
    print('BASR_DIR',BASR_DIR)

    # img_abs_path = os.path.join(BASR_DIR,img_path)
    # print(img_abs_path)       #没有拼接成功
    img_abs_path = '%s%s'%(BASR_DIR,img_path)
    print('img_abs_path',img_abs_path)
    if os.path.isfile(img_abs_path):
        print('*************file exsit.....')
        f = open(img_abs_path,'rb')
        data = f.read()#   图片文件内容
        return [data,0] #0代表没错，1代表有错
    return [None,1]
def run_server(environ,start_response):
    print('hahahah')

    urls = url_dispacher()     #拿到所有的url
    requests_url = environ.get('PATH_INFO')
    print('request url',requests_url)
    if requests_url in urls:
        func = urls[requests_url](environ,start_response)
        return func     #真正返回数据给用户
    elif requests_url.startswith("/static/"): #代表是图片
        img_data,img_status = img_hander(requests_url)
        if img_status==0:
            print('有内容啊啊啊啊啊啊')
            start_response('200 OK', [('Content-type', 'text/jpeg;charset=utf-8')])
            return [img_data]   #返回列表类型
    else:
        start_response('404',[('Content-type','text/html;charset=utf-8')])
        return [bytes('<h1 style="font-size=50px">Page not Found!!!</h1>',encoding='utf-8')]

if __name__ == '__main__':
    httpd = make_server('localhost',8001,run_server)
    httpd.serve_forever()
